﻿using System;

namespace RoketSolutions.SP2010.Infrostructure.UI.Ajax.Controllers
{
    public class ControllerDescriptor
    {
        private readonly ActionMethodSelector actionSelector;
        private readonly ControllerBase controller;
        private static Cache<String, ActionDescriptor> descriptorCache = new Cache<String, ActionDescriptor>();

        public ControllerDescriptor(ControllerBase controller)
        {
            this.controller = controller;
            actionSelector = new ActionMethodSelector(this);
        }

        public ActionDescriptor FindActionMethod(String actionName)
        {
            if(String.IsNullOrEmpty(actionName))
                throw new ArgumentException("Action name cannot be empty.");

            return DescriptorCache.GetEntry(GetActionKey(controller, actionName),
                                                 () =>
                                                 new ActionDescriptor(this, actionSelector.FindActionMethod(actionName)));
        }

        private String GetActionKey(ControllerBase controller, String actionName)
        {
            return String.Format("{0}{1}", controller.GetType(), actionName);
        }

        public ControllerBase Controller
        {
            get
            {
                return controller;
            }
        }

        public Cache<String, ActionDescriptor> DescriptorCache
        {
            get
            {
                return descriptorCache;
            }
        }
    }
}
